#include "GameofLife.h"

char** GameofLife::buildGrid(int R, int C) const{
       char** Res = new char*[R];
       for(int i=0;i<R;i++) {
			Res[i] = new char[C+1];   
			Res[i][C]=(char)0;
		    }
        return Res; 
        }

char** GameofLife::copyGrid(char** gridToBeCopied, int R, int C) const{
       char** Res = buildGrid(R, C);
       for(int i=0; i<R; i++)
          for(int j=0; j<C; j++)
             Res[i][j] = gridToBeCopied[i][j];
       return Res;       
       
       }
       
void GameofLife::deallocateGrid(){
     for(int i=0; i<Row;i++)
             delete[] Grid[i];
     delete[] Grid;
     }
  
void GameofLife::setGridElt(int i, int j, char Mark){
       if((i>=0)&&(i<Row))
          if((j>=0)&&(j<Col)){
              Grid[i][j] = Mark;
	          return;
           }
       throw "invalid input to GameofLife::setGridElt";
       }
       
int GameofLife::countLitNeighbors(int i, int j) const{
    int x = 0; // number of lit neighbours  
    int top = (i+1<Row)?i+1:0;
    if(isLit(top, j)) x++;
    if(isLit(top, j?j-1:Col-1)) x++;
    if(isLit(top, j+1<Col?j+1:0)) x++;
    
    if(isLit(i, j?j-1:Col-1)) x++;
    if(isLit(i, j+1<Col?j+1:0)) x++;
    
    int bot = (i)?i-1:Row-1;
    if(isLit(bot, j)) x++;
    if(isLit(bot, j?j-1:Col-1)) x++;
    if(isLit(bot, j+1<Col?j+1:0)) x++;
    
    return x;
       }

bool GameofLife::isLitInNextEvolution(int i, int j) const{
	int x = countLitNeighbors(i,j); //know state of cells around cell.
	//POPULATED
	if(isLit(i,j)){
		if((x <= 1)||(x >= 4)) return false;
		return true;
	}
    //UNPOPULATED
    if(x == 3) return true;	//Start living
	return false;
    }
    
void GameofLife::evolve( ){
     GameofLife newGame(Row, Col);
     for (int i =0; i<Row; i++)
	     for(int j =0; j< Col;j++)
           if (isLitInNextEvolution(i,j)) newGame.lightCell(i,j);
	deallocateGrid();
	Grid = copyGrid(newGame.Grid, Row, Col);
}     
